package uk.co.q3c.deplan.server.domain.util;

import java.io.Serializable;
import java.util.Date;
import java.util.TreeSet;

import javax.persistence.Id;

import uk.co.q3c.deplan.client.domain.AbstractDomainObject;
import uk.co.q3c.deplan.client.domain.util.DateProfileEntry;
import uk.co.q3c.deplan.client.service.ServiceFactory;
import uk.co.q3c.deplan.client.util.Q3DateUtil;

import com.googlecode.objectify.annotation.Cached;
import com.googlecode.objectify.annotation.Unindexed;

@Unindexed
@Cached(expirationSeconds = 600)
public abstract class DailyProfile_TreeSet<E extends DateProfileEntry> extends AbstractDomainObject implements Serializable {

	private static final long serialVersionUID = 1L;
	@Id
	private Long keyId;

	protected DailyProfile_TreeSet() {
		super();
	}

	public DailyProfile_TreeSet(ServiceFactory connection) {
		super(connection);
	}

	/**
	 * Duplicate and null rejected, but no exception. It is expected that entries would generally be added at the end of the list, so this
	 * method is biased towards that situation for performance
	 * 
	 * @param entry
	 */
	public void addEntry(E newEntry) {
		profile().add(newEntry);
	}

	public E getEntry(String dateKey) {
		return find(dateKey);
	}

	/**
	 * This could be made quicker by using a split search
	 * 
	 * @param dateKey
	 * @return
	 */
	private E find(String dateKey) {
		E result = null;
		for (E entry : profile()) {
			if (entry.getDateKey().equals(dateKey)) {
				result = entry;
				break;
			}
		}
		return result;
	}

	public E getEntry(Date date) {
		return getEntry(Q3DateUtil.dateToKey(date));
	}

	public int size() {
		return profile().size();
	}

	public E first() {
		return profile().first();
	}

	public E last() {
		return profile().last();
	}

	abstract protected TreeSet<E> profile();

	public void clear() {
		for (E entry : profile()) {
			entry.clear();
		}

	}

	public Long getKeyId() {
		return keyId;
	}
}